package xin.mashibo.wanjiobutest.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.wanji.etcble.bean.ServiceStatus;
import com.wanji.etcble.constants.BuleCommonConstants;
import com.wanji.etcble.service.WJBleAPI;

import java.util.concurrent.TimeUnit;

import xin.mashibo.wanjiobutest.R;
import xin.mashibo.wanjiobutest.service.ObuOptService;
import xin.mashibo.wanjiobutest.vo.LoadInitCreditExtend;

import static xin.mashibo.wanjiobutest.constant.ServiceConstant.MAC1_KEY;
import static xin.mashibo.wanjiobutest.constant.ServiceConstant.MSG_CONNECT;
import static xin.mashibo.wanjiobutest.constant.ServiceConstant.MSG_DISCONNECT;
import static xin.mashibo.wanjiobutest.constant.ServiceConstant.MSG_MAC1;
import static xin.mashibo.wanjiobutest.constant.ServiceConstant.MSG_READCARD;
import static xin.mashibo.wanjiobutest.constant.ServiceConstant.MSG_READCONSUME;
import static xin.mashibo.wanjiobutest.constant.ServiceConstant.MSG_READDEVICE;
import static xin.mashibo.wanjiobutest.constant.ServiceConstant.MSG_READOWNER;
import static xin.mashibo.wanjiobutest.constant.ServiceConstant.MSG_TRANSACTION;
import static xin.mashibo.wanjiobutest.constant.ServiceConstant.NONE_READCARD;
import static xin.mashibo.wanjiobutest.constant.ServiceConstant.isSuccess;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";

    /**
     * 申请权限请求码
     */
    public static final int REQUEST_PERMIT_BLUETOOTH = 1;
    /**
     * 申请开启蓝牙
     */
    public static final int ENABLE_BLUETOOTH_REQUESTCODE = 1;

    private WJBleAPI wjApi;

    private Button connect;

    private Button disConnect;

    private Button readCard;

    private Button readOwner;

    private Button readConsume;

    private Button readDevice;

    private Button readTransaction;

    private Button readMac1;

    private EditText incMny;

    private EditText mac2Input;

    private Button writeCard;

    private ProgressDialog progressDialog;

    private Handler handler;

    private ObuOptService service;

    private BluetoothAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wjApi = WJBleAPI.getInstance();
        handler = new Handler(new MyHandlerCallBack());
        service = new ObuOptService(wjApi, handler);
        adapter = BluetoothAdapter.getDefaultAdapter();
        initView();
    }

    /**
     * 初始化页面视图
     */
    private void initView() {
        connect = findViewById(R.id.connect);
        disConnect = findViewById(R.id.disconnect);
        readCard = findViewById(R.id.readCard);
        readOwner = findViewById(R.id.readOwner);
        readConsume = findViewById(R.id.readConsume);
        readDevice = findViewById(R.id.readDevice);
        readTransaction = findViewById(R.id.readTransaction);
        readMac1 = findViewById(R.id.readMac1);
        incMny = findViewById(R.id.incMny);
        mac2Input = findViewById(R.id.mac2_input);
        writeCard = findViewById(R.id.writeCard);
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("正在处理中");
        progressDialog.setCancelable(false);
        connect.setOnClickListener(this);
        disConnect.setOnClickListener(this);
        readCard.setOnClickListener(this);
        readOwner.setOnClickListener(this);
        readConsume.setOnClickListener(this);
        readDevice.setOnClickListener(this);
        readTransaction.setOnClickListener(this);
        readMac1.setOnClickListener(this);
        writeCard.setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (Build.VERSION.SDK_INT < 22) {
            permitBluetooth();
        } else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_PERMIT_BLUETOOTH);
            } else {
                permitBluetooth();
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v instanceof Button) {
            if (v.getId() != R.id.connect && !BuleCommonConstants.conflag) {
                Toast.makeText(this, "尚未连接蓝牙OBU", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!progressDialog.isShowing()) {
                progressDialog.show();
            }
        }
        switch (v.getId()) {
            case R.id.connect:
                service.connect();
                break;
            case R.id.disconnect:
                service.disConnect();
                break;
            case R.id.readCard:
                service.readCard();
                break;
            case R.id.readOwner:
                service.readCardOwner();
                break;
            case R.id.readConsume:
                service.readConsume();
                break;
            case R.id.readDevice:
                service.readDevice();
                break;
            case R.id.readTransaction:
                service.readTransaction();
                break;
            case R.id.readMac1:
                Editable editable = incMny.getText();
                if (editable == null) {
                    Toast.makeText(this, "请输入充值金额", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        int credit = Integer.parseInt(editable.toString());
                        if (credit <= 0) {
                            Toast.makeText(this, "金额错误，请重新输入", Toast.LENGTH_SHORT).show();
                        } else {
                            service.readMac1(credit);
                        }
                    } catch (NumberFormatException e) {
                        Log.e(TAG, "onClick: " + e.getMessage(), e);
                        Toast.makeText(this, "金额错误，请重新输入", Toast.LENGTH_SHORT).show();
                    }
                }

                break;
            case R.id.writeCard:
                Editable mac2 = mac2Input.getText();
                if (mac2 == null) {
                    Toast.makeText(this, "请输入MAC2", Toast.LENGTH_SHORT).show();
                } else {
                    if (mac2.length() != 22) {
                        Toast.makeText(this, "MAC2格式错误", Toast.LENGTH_SHORT).show();
                    } else {
                        Log.i(TAG, "MAC2：" + mac2.toString());
                        service.writeCard(mac2.toString());
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMIT_BLUETOOTH:
                if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "未开启权限，无法使用该功能", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    permitBluetooth();
                }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ENABLE_BLUETOOTH_REQUESTCODE) {
            if (resultCode != RESULT_OK) {
                Toast.makeText(this, "拒绝开启蓝牙，无法使用该功能", Toast.LENGTH_SHORT).show();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    Log.d(TAG, "onActivityResult: " + e.getMessage(), e);
                }
                finish();
            }
        }
    }

    private void permitBluetooth() {
        if (adapter == null) {
            Toast.makeText(this, "该设备不支持蓝牙功能", Toast.LENGTH_SHORT).show();
            finish();
        } else if (!adapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, ENABLE_BLUETOOTH_REQUESTCODE);
        }
    }

    class MyHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.obj == null || !(msg.obj instanceof ServiceStatus)) {
                return false;
            }
            ServiceStatus status = (ServiceStatus) msg.obj;
            switch (msg.what) {
                case MSG_CONNECT:
                    Toast.makeText(MainActivity.this, isSuccess(status) ? "连接成功" : status.getServiceInfo(), Toast.LENGTH_SHORT).show();
                    break;
                case MSG_DISCONNECT:
                    Toast.makeText(MainActivity.this, isSuccess(status) ? "成功断开连接" : status.getServiceInfo(), Toast.LENGTH_SHORT).show();
                    break;
                case MSG_READCARD:
                    if (!isSuccess(status)) {
                        Toast.makeText(MainActivity.this, "读取卡片信息失败", Toast.LENGTH_SHORT).show();
                    } else {
                        CardInfoActivity.actionStart(MainActivity.this, msg.getData());
                    }
                    break;
                case MSG_READOWNER:
                    if (!isSuccess(status)) {
                        Toast.makeText(MainActivity.this, "读取卡片所有人信息失败", Toast.LENGTH_SHORT).show();
                    } else {
                        CardOwnerActivity.actionStart(MainActivity.this, msg.getData());
                    }
                    break;
                case MSG_READCONSUME:
                    if (!isSuccess(status)) {
                        Toast.makeText(MainActivity.this, "读取卡片消费记录失败", Toast.LENGTH_SHORT).show();
                    } else {
                        CardConsumeActivity.actionStart(MainActivity.this, msg.getData());
                    }
                    break;
                case MSG_READDEVICE:
                    if (!isSuccess(status)) {
                        Toast.makeText(MainActivity.this, "读取设备信息失败", Toast.LENGTH_SHORT).show();
                    } else {
                        DeviceInfoActivity.actionStart(MainActivity.this, msg.getData());
                    }
                    break;
                case MSG_TRANSACTION:
                    if (!isSuccess(status)) {
                        int serviceCode = status.getServiceCode();
                        if (serviceCode == NONE_READCARD) {
                            Toast.makeText(MainActivity.this, "请先读取卡片信息", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "读取卡片交易信息失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        TransactionActivity.actionStart(MainActivity.this, msg.getData());
                    }
                    break;
                case MSG_MAC1:
                    if (!isSuccess(status)) {
                        int serviceCode = status.getServiceCode();
                        if (serviceCode == NONE_READCARD) {
                            Toast.makeText(MainActivity.this, "请先读取卡片信息", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "读取MAC1相关数据失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Bundle bundle = msg.getData();
                        LoadInitCreditExtend extend = (LoadInitCreditExtend) bundle.get(MAC1_KEY);
                        InitCreditActivity.actionStart(MainActivity.this, bundle);
                    }
                    break;
                default:
                    break;

            }
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            return true;
        }
    }


}
